package com.amumu.netctoss.util;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.amumu.netctoss.entity.Privilege;

public class PrivilegeReader {
	private static List<Privilege> privileges;
	private static Map<String,Privilege> mapPri= new HashMap<String, Privilege>();
	static {
		InputStream is = PrivilegeReader.class.getClassLoader().getResourceAsStream("privileges.xml");
		privileges = loadPrivileges(is);
	}

	private static List<Privilege> loadPrivileges(InputStream is) {
		SAXReader reader = new SAXReader();
		Document doc = null;
		try {
			doc = reader.read(is);
		} catch (DocumentException e1) {
			e1.printStackTrace();
		}
		Element root = doc.getRootElement();
		List<Element> elmts = root.elements();
		List<Privilege> privs = new ArrayList<Privilege>();
		for (Element e : elmts) {
			Privilege p = new Privilege();
			p.setId(e.attributeValue("id"));
			p.setName(e.elementText("name"));
			Element urlElemts = e.element("urls");
			List<Element> urls = urlElemts.elements();
			List<String> list = new ArrayList<String>();
			for(Element et:urls){
				list.add(et.getText());
			}
			p.setUrls(list);
			mapPri.put(p.getId(), p);
			privs.add(p);
		}
		return privs;
	}
	
	public static List<Privilege> getPrivileges() {
		return privileges;
	}

	public static Map<String, Privilege> getMapPri() {
		return mapPri;
	}

	public static void main(String[] args) {
		List<Privilege> list = PrivilegeReader.getPrivileges();
		for(Privilege p:list){
			System.out.println(p.getId()+","+p.getName());
			for(String str:p.getUrls())
			System.out.println(str);
		}
	}
}
